<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="chart-card">
          <div ref="buildingChart" style="height:400px"></div>
        </el-card>
      </el-col>
      <el-col :span="24" style="margin-top:20px">
        <el-card class="chart-card">
          <div ref="applicationChart" style="height:400px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount} from 'vue'
import * as echarts from 'echarts'
import http from '@/utils/http.js'
import {ElMessage} from 'element-plus'

// 图表实例
const buildingChart = ref(null)
const applicationChart = ref(null)
let buildingChartInstance = null
let applicationChartInstance = null

// 初始化图表
const initCharts = () => {
  // 楼栋入住统计
  buildingChartInstance = echarts.init(buildingChart.value)
  buildingChartInstance.setOption({
    title: {text: '各楼栋入住情况分析', left: 'center'},
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let res = params[0].name + '<br>'
        params.forEach(p => {
          res += `${p.marker} ${p.seriesName}: ${p.value}`
          res += '<br>'
        })
        return res
      }
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {type: 'value'},
    series: [
      {
        name: '设计床位',
        type: 'bar',
        data: [],
        itemStyle: {color: '#5470c6'}
      },
      {
        name: '已入住',
        type: 'bar',
        data: [],
        itemStyle: {color: '#91cc75'},
      },
      // {
      //   name: '待入住',
      //   type: 'bar',
      //   data: [],
      //   itemStyle: {color: '#e6c23a'}
      // },
      // {
      //   name: '待退住',
      //   type: 'bar',
      //   data: [],
      //   itemStyle: {color: '#e67373'}
      // }
    ]
  })

  // 申请占比统计
  applicationChartInstance = echarts.init(applicationChart.value)
  applicationChartInstance.setOption({
    title: {text: '申请占比分析', left: 'center'},
    tooltip: {
      trigger: 'axis',
      valueFormatter: (value) => value + '%'
    },
    legend: {
      data: ['入住申请率', '退住申请率'],
      bottom: 0
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '百分比 (%)',
      axisLabel: {formatter: '{value}%'},
      max: 100
    },
    series: [
      {
        name: '入住申请率',
        type: 'line',
        data: [],
        itemStyle: {color: '#67C23A'},
        symbol: 'circle',
        symbolSize: 8
      },
      {
        name: '退住申请率',
        type: 'line',
        data: [],
        itemStyle: {color: '#E6A23C'},
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  })
}

// 获取真实数据
const fetchData = async () => {
  try {
    const res = await http.get('/building/statistics')
    const apiData = res.data

    // 转换数据结构
    const buildings = apiData.map(item => ({
      name: item.name,
      total: item.total,
      current: item.current,
      checkinApps: item.checkinApps,
      checkoutApps: item.checkoutApps
    }))

    // 更新楼栋统计图表
    buildingChartInstance.setOption({
      xAxis: {
        data: buildings.map(b => ({
          value: b.name,
          total: b.total,
          current: b.current,
          remaining: b.total - b.current
        }))
      },
      series: [
        {data: buildings.map(b => b.total)},
        {data: buildings.map(b => b.current)},
        // {data: buildings.map(b => b.checkinApps)},
        // {data: buildings.map(b => b.checkoutApps)}
      ]
    })

    // 更新申请占比图表
    applicationChartInstance.setOption({
      xAxis: {data: buildings.map(b => b.name)},
      series: [
        {


          data: buildings.map(b =>
              b.current > 0
                  ? (b.checkinApps / b.total * 100).toFixed(1)
                  : 0
          )
        },
        {
          data: buildings.map(b =>
              b.current > 0
                  ? (b.checkoutApps / b.total * 100).toFixed(1)
                  : 0
          )
        }
      ]
    })

  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('数据加载失败')
  }
}

onMounted(() => {
  initCharts()
  fetchData()
  window.addEventListener('resize', () => {
    buildingChartInstance?.resize()
    applicationChartInstance?.resize()
  })
})

onBeforeUnmount(() => {
  buildingChartInstance?.dispose()
  applicationChartInstance?.dispose()
})
</script>

<style scoped>
.chart-card {
  margin: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}
</style>
